import os
import uvicorn
from fastapi import FastAPI, HTTPException, Depends, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
from dotenv import load_dotenv
from loguru import logger

# 导入自定义模块
from api.router import router as api_router
from dependencies import get_neo4j_client, get_ollama_client, get_answer_generator, neo4j_client, ollama_client

# 加载环境变量
load_dotenv()

# 配置日志
log_level = os.getenv("LOG_LEVEL", "INFO")
logger.add("logs/app.log", rotation="500 MB", level=log_level)

# 创建FastAPI应用
app = FastAPI(
    title="知识图谱问答系统API",
    description="基于Neo4j知识图谱和DeepSeek-R1:70b大语言模型的智能问答系统",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该限制来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(api_router, prefix="/api")

# 依赖注入

# 健康检查端点
@app.get("/health")
async def health_check():
    return {"status": "healthy", "version": "1.0.0"}

# 启动事件
@app.on_event("startup")
async def startup_event():
    logger.info("应用启动中...")
    # 测试Neo4j连接
    try:
        neo4j_client.test_connection()
        logger.info("Neo4j连接成功")
    except Exception as e:
        logger.error(f"Neo4j连接失败: {str(e)}")
    
    # 测试Ollama连接
    try:
        await ollama_client.test_connection()
        logger.info("Ollama连接成功")
    except Exception as e:
        logger.error(f"Ollama连接失败: {str(e)}")

# 关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    logger.info("应用关闭中...")
    # 关闭Neo4j连接
    neo4j_client.close()

if __name__ == "__main__":
    # 获取环境变量或使用默认值
    host = os.getenv("HOST", "0.0.0.0")
    port = int(os.getenv("PORT", "1234"))
    debug = os.getenv("DEBUG", "False").lower() == "true"
    
    # 启动服务器
    uvicorn.run("main:app", host=host, port=port, reload=debug)